const express     = require("express");
const fs          = require("fs");
const http        = require("http");
const Primus      = require("primus");
const CryptoJS    = require("crypto-js");
const NodeRSA     = require('node-rsa');
const querystring = require('querystring');

const CMDMAP =  require('./map').CMDMAP;

/* const publicKey = '\
-----BEGIN PUBLIC KEY-----\
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbOLOB5z6T1aG5yVe6S1UJzbH4\n\
iSUoRB/ETx/YGmMqRwE1XneulWxBeg2eeEKs+jFbFj0QiM4AmZnusFC/tgz3Qyzs\n\
ArDsnaUhKoF01GwLZL6VkgYefAowYLAfO4LmRhO8L0sflkw2HfjpgyfumqXLR/nO\n\
4aaOlQp584uKP1zU/wIDAQAB\n\
-----END PUBLIC KEY-----\
'; */

var publicKey = "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBfpHPxGFzE1nbiNiSwmTEoyVI2cDpmFHd0AGfRvlsJX+IuXqx19Oaw7BbgLBONS4hRKfFscHv5Bx6S31MAiGAke98/c1uuXGJ5bGYqEKXBbxP4K+c+pL1yVkXkEo622ztvfZ19gwvnIl08uR9G44dNiCEqtafi5zHWrwXIveTs0K5lqxpSyL6+hmcrTxxOJB6fwcq75F5guXqubSfP3Y2G66ybKMVnRot2wmmkJ38aH1IsrSL9Lyn6pZpMqdxmLPYYmyOqFpePUD3qYMRycFFr51HtdsLFb0Z7vvF9RTYLt3bwQHew7LXAiBd5eU4kfQxUbmj3Gc1AClpUsc3pBLUXAgMBAAE="


var privateKey = "\
-----BEGIN RSA PRIVATE KEY-----\
MIIEoQIBAAKCAQBfpHPxGFzE1nbiNiSwmTEoyVI2cDpmFHd0AGfRvlsJX+IuXqx1\
9Oaw7BbgLBONS4hRKfFscHv5Bx6S31MAiGAke98/c1uuXGJ5bGYqEKXBbxP4K+c+\
pL1yVkXkEo622ztvfZ19gwvnIl08uR9G44dNiCEqtafi5zHWrwXIveTs0K5lqxpS\
yL6+hmcrTxxOJB6fwcq75F5guXqubSfP3Y2G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s5SufVOy\
4C3hzBs751pqzvJqqcC+o9jn3CNsrPjMe1PXZqWpihs25zo6F0QacWEwQlSMqwYR\
yPI4mrKMtFDFiZHnfWgaMva793gIKsJFHxee+eX71W6bFCzcWFypGQ0uoMiewjqO\
qeECgYAiXg+hx2KAy7DrK/NHNY9SeMSqAU0g6HlEToZHQVcngmGTGEO3eDutqVLr\
XqY2bLSWYE16HeiRELfR12XwvBYDpN9wz8ofAgLdGsMC4BhHoRM2Dd3ckOBN/yrE\
sHu6oTdaBQ/BZFS48f1zBnbIdtFhzjox5oDkLOwKKC0KYujzhw==\
-----END RSA PRIVATE KEY-----\
";


module.exports = function(app) {
	initExpress(app||express());

	let server = http.createServer( /*app*/ );
	let primus = new Primus(server);
	let encryptedString, commonKey;

	let key = new NodeRSA(privateKey);
	key.setOptions({ encryptionScheme: "pkcs1" });


	server.listen(3000, () => console.log('listening on *:3000'));

	primus.on('open', data => console.log("连接成功", data));
	primus.on('connection', spark => {
		spark.emit("incoming::open");
		spark.on('data', data => {
			if (!spark.commonKey) {
				let txt = String(spark.query.login).replace(/\ /g, "+");
				let decrypted = key.decrypt(txt, "utf8");
				commonKey = spark.commonKey = getQueryString("commKey", decrypted);
			}
			let parsedData = decryptDataFunc(data);
			console.log('客户端:', parsedData);
			let cmd = parsedData.cmd || "conn::error";
			cmd = CMDMAP[cmd] || cmd;
			fs.readFile(`server/data/${cmd}.json`, 'utf8', (err, data) => {
				let resdata;
				if (err) {
					cmd = "conn::error", resdata = {
						"statusCode": "0000",
						"msg": "SYS_ERROR"
					};
				} else {
					resdata = JSON.parse(data);
				}
				setTimeout(()=> spark.write(encryptDataFunc(resdata)) , 10 );

				if (cmd=="loading" && !spark.loading_flag) {
					spark.loading_flag = true;
					setTimeout(()=> spark.write(encryptDataFunc({
						"cmd": "start",
						"code": 0,
						"res": 0
					})) , 500 );
				}
			});


			if (cmd=="start") {
				console.log('战斗开始:');
				sendSyncData(spark);
			}
			
		});
	});

	

	let syncTimer;
	function sendSyncData(spark) {
		clearInterval();
		syncTimer = setInterval(()=> {
			fs.readFile(`server/data/sync.json`, 'utf8', (err, data) => {
				let resdata = JSON.parse(data);
				spark.write(encryptDataFunc(resdata));
			});
		}, 5000);
	}



	function encryptDataFunc(resdata) {
		let encryptData = CryptoJS.AES.encrypt(JSON.stringify(resdata), CryptoJS.enc.Utf8.parse(commonKey), {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		return encryptData.toString();
	}

	function decryptDataFunc(data) {
		let decryptstr = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(commonKey), {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		let dataString = decryptstr.toString(CryptoJS.enc.Utf8);
		return JSON.parse(dataString);
	}

	function getQueryString(name, str) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = str.match(reg);
		if (r !== null) {
			return querystring.unescape(r[2]);
		}
		return null;
	};


};

function initExpress(app) {
	app.get("/", (req, res, next) => {
		if (req.query.act) {
			let q = req.query.st || req.query.act;
			fs.readFile(`server/data/${q}.json`, (err, data) => {
				let resdata = err? { "code": "404", "msg": "SYS_ERROR" }: JSON.parse(data);
				res.json(resdata);
			});
			return;
		}
		next();
	});
}